// rs_log.cpp: functions for logging 
#include <iostream>
#include "rs_log.h"
using namespace std;

rs_ostream* log_ofs;
static bool flush_after_write=true;
static bool log_time_stamps=false;

void rs_log_set_time_stamps (bool value)
{
    log_time_stamps = value;
}

#include <sys/timeb.h>


void rs_log_base (const rs_string& message, bool to_console, const rs_string& key)
{
    // todo: if key is nonempty and already seen and suitable option is set, suppress writing to console/file
    // this way, specific message is able to be reported once
    rs_string time_stamp;
    if (log_time_stamps) {
        struct _timeb time_now;
        _ftime_s (&time_now);
        char time_str[13];
        int seconds = (int) (time_now.time % (3600 * 24));
        int hh = seconds / 3600;
        seconds %= 3600;
        int mm = seconds / 60;
        int ss = seconds % 60;
        sprintf_s (time_str, 13, "%02d:%02d:%02d:%03d",
            hh, mm, ss, time_now.millitm);
        string stamp_str (time_str, 12);
        time_stamp = rs_stringed (stamp_str + " ");
    }
    if (to_console)
        cout << stringed (message);
    if (log_ofs) {
        log_ofs->write_line (time_stamp + message, false);
        if (flush_after_write)
            log_ofs->flush();
    }
}


